<?php
/**
 * @ClassName: Membercation
 * @Description: 实名认证
 * @author: gydtrade
 * @Date: 2024-09-10 22:13
 * @Version: V1.0.0
 */

namespace app\admin\controller;

use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Membercation extends Controller
{
    use HasBuilder;

    protected $dataModel;

    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\MemberCation();
        $this->pageTitle = '实名认证';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->indexWith = [];

        $this->selectTextField = '{realname}({idcard})';
        $this->selectFields = 'id,realname,idcard';
        $this->selectSearch = 'realname|idcard';
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;
        $search->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'));
        $search->text('name', '实名信息');
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        if (!empty($searchData['member_id'])) {
            $where[] = ['member_id', 'eq', $searchData['member_id']];
        }
        if (!empty($searchData['name'])) {
            $where[] = ['realname|idcard', 'like', '%' . $searchData['name'] . '%'];
        }
        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->match('nickname', '会员');
        $table->fields('info', '实名信息')->with(
            $table->show('realname', '真实姓名'),
            $table->show('idcard', '身份证号'),
            $table->show('sex', '性别')
        );
        $table->show('nation', '民族');
        $table->show('birthday', '生日');
        $table->show('address', '地址');
        $table->image('card_front', '身份证正面')->thumbSize(100, 80);
        $table->image('card_back', '身份证反面')->thumbSize(100, 80);
        $table->match('status', '认证状态')->mapClassGroup([[0, 'info'], [1, 'success'], [2, 'danger']]);

        $table->fields('times', '认证/修改时间')->with(
            $table->show('create_time', '认证时间'),
            $table->show('update_time', '修改时间')
        )->getWrapper()->addStyle('width:160px');

        $table->sortable('id, create_time');

        foreach ($data as &$d) {
            $d['__h_p__'] = $d['status'] != 0;
            $d['__h_unp__'] = $d['status'] != 0;
        }
        unset($d);

        $table->getToolbar()
            ->btnAdd()
            ->btnEnableAndDisable('通过', '拒绝')
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnDelete()
            ->btnView()
            ->btnPostRowid('pass', url('enable', ['state' => 1]), '通过', 'btn-success', '', '')
            ->btnPostRowid('unpass', url('enable', ['state' => 0]), '拒绝', 'btn-danger', '', '')
            ->mapClass([
                'pass' => ['hidden' => '__h_p__'],
                'unpass' => ['hidden' => '__h_unp__'],
            ]);
    }

    /**
     * 审核
     * @param $state
     * @return \think\response\Json
     */
    public function enable($state)
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => '参数有误']);
        }

        if ($state) {
            $remark = '审核通过';
            $status = 1;
        } else {
            $remark = '审核不通过';
            $status = 2;
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, $remark, $status)) {
                $res += 1;
            }
        }
        if ($res) {
            return json(['code' => 1, 'msg' => '成功操作' . $res . '条数据']);
        } else {
            trace('审核操作失败');
            return json(['code' => 0, 'msg' => '审核操作失败']);
        }
    }

    /**
     * 审核操作
     * @param $id
     * @param $remark
     * @param $state
     * @return model\OperationCenter|\think\response\Json
     */
    private function trans($id, $remark, $state = 1)
    {
        $records = $this->dataModel::where('id', $id)->find();

        if (!$records) {
            return json(['code' => 0, 'msg' => '记录不存在']);
        }
        if ($records['status'] != 0) {
            return json(['code' => 0, 'msg' => '记录状态不是待审核状态']);
        }

        $up_data = [
            'status' => $state,
            'review_opinion' => $remark,
            'update_time' => date_now(),
        ];
        if ($state == 1) {
            $up_data['review_time'] = date_now();
        }
        $res = $this->dataModel::where('id', $id)->update($up_data);

        return $res;
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;
        $form->select('member_id', '会员')->dataUrl(url('/admin/member/selectPage'))->required();
        $form->text('realname', '真实姓名')->required();
        $form->text('idcard', '身份证号')->maxlength(18)->required();
        $form->text('sex', '性别')->required();
        $form->text('nation', '民族')->required();
        $form->date('birthday', '生日')->required();
        $form->textarea('address', '地址')->required();
        $form->image('card_front', '身份证正面')->thumbSize(100, 80)->required();
        $form->image('card_back', '身份证反面')->thumbSize(100, 80)->required();
        $form->radio('status', '认证状态')->default(1)->required()->when(2)->with(
            $form->textarea('review_opinion', '审核意见')->required()
        );

        if ($isEdit) {
            $form->show('create_time', '认证时间');
            $form->show('update_time', '修改时间');
        }
    }

    /**
     * 保存数据
     * @param $id
     * @return mixed|\think\response\Json
     */
    private function save($id = 0)
    {
        $data = request()->only([], 'post');

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();

            $where = " (member_id = " . $data['member_id'] . " or idcard = " . $data['idcard'] . ") and id <> " . $id;
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();

            $where = " member_id = " . $data['member_id'] . " or idcard = " . $data['idcard'];
        }
        $record = $this->dataModel::where($where)->find();
        if ($record) {
            return json(['code' => 0, 'msg' => '当前用户已经实名认证，请勿重复认证']);
        }

        return $this->doSave($data, $id);
    }

}